// 时间格式化
/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time)
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
            // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
    if (('' + time).length === 10) {
        time = parseInt(time) * 1000
    } else {
        time = +time
    }
    const d = new Date(time)
    const now = Date.now()

    const diff = (now - d) / 1000

    if (diff < 30) {
        return '刚刚'
    } else if (diff < 3600) {
        // less 1 hour
        return Math.ceil(diff / 60) + '分钟前'
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前'
    } else if (diff < 3600 * 24 * 2) {
        return '1天前'
    }
    if (option) {
        return parseTime(time, option)
    } else {
        return (
            d.getMonth() +
            1 +
            '月' +
            d.getDate() +
            '日' +
            d.getHours() +
            '时' +
            d.getMinutes() +
            '分'
        )
    }
}
/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'deepClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    Object.keys(source).forEach(keys => {
        if (source[keys] && typeof source[keys] === 'object') {
            targetObj[keys] = deepClone(source[keys])
        } else {
            targetObj[keys] = source[keys]
        }
    })
    return targetObj
}
export function zeroFill(num) {
    if (typeof num !== 'number') return
    num = num < 10 ? `0${num}` : num
    return num
}
// 电话验证
export function validityPhone(phone) {
	const phoneReg = /^1[3456789]\d{9}/
	return phoneReg.test(phone)
}
// base64 转语音
export function dataURL2Audio (base64Str, callback, platform) {
    var base64Str = base64Str.replace('data:audio/mp3;base64,','');
    var audioName = (new Date()).valueOf() + '.mp3';  

    plus.io.requestFileSystem(plus.io.PRIVATE_DOC,function(fs){  
        fs.root.getFile(audioName,{create:true},function(entry){  
            // 获得平台绝对路径  
            var fullPath = entry.fullPath;  
            if( platform === 'android'){    
                // 读取音频  
                var Base64 = plus.android.importClass("android.util.Base64");  
                var FileOutputStream = plus.android.importClass("java.io.FileOutputStream");  
                try{  
                    var out = new FileOutputStream(fullPath);  
                    var bytes = Base64.decode(base64Str, Base64.DEFAULT);  
                    out.write(bytes);   
                    out.close();  
                    // 回调  
                    callback && callback(entry);  
                }catch(e){  
                    console.log(e.message);  
                }  
            }else if(platform === 'ios'){  
                var NSData = plus.ios.importClass('NSData');  
                var nsData = new NSData();  
                nsData = nsData.initWithBase64EncodedStringoptions(base64Str,0);  
                if (nsData) {  
                    nsData.plusCallMethod({writeToFile: fullPath,atomically:true});  
                    plus.ios.deleteObject(nsData);  
                }  
                // 回调  
                callback && callback(entry);  
            }  
        })  
    })  
}
// 音频转base64
export function Audio2dataURL (path,callback) {  
    plus.io.resolveLocalFileSystemURL(path, function(entry){  
        entry.file(function(file){  
            var reader = new plus.io.FileReader();  
            reader.onloadend = function (e) {
							callback(e.target.result)
            };  
            reader.readAsDataURL(file);  
        },function(e){  
            
        })  
    })  
}  